home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11245 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  59 lines

  1. Path: damon.irf.uni.dortmund.de!broth
  2. From: rothert@damon.irf.uni-dortmund.de (Bernd Rothert)
  3. Newsgroups: comp.lang.c++
  4. Subject: Lifetime of temporary parameter objects
  5. Date: Wed, 13 Mar 96 09:49:14 GMT
  6. Organization: Institute of Robotics Research
  7. Message-ID: <4i6607$l4q@damon.irf.uni-dortmund.de>
  8. NNTP-Posting-Host: broth.irf
  9. X-Newsreader: News Xpress Version 1.0 Beta #4
  10.  
  11.  
  12. I need some advice concerning the lifetime of temporary parameter objects in
  13. function calls:
  14.  
  15. It is obviously correct to pass a reference to a temporary object to a
  16. function - the compiler ensures that the temporary stays alive as long
  17. as the reference exists (actual parameter of "const Stars&").
  18.  
  19. What if passing a pointer to the CONTENTS of an explicitly constructed
  20. temporary:
  21.  
  22. ---
  23. #include <string.h>
  24. #include <iostream.h>
  25. class Stars {
  26.   public:
  27.     Stars(int n) : _s(new char[n+1]) {
  28.         memset(_s, '*', n);
  29.         _s[n] = '\0';
  30.     }
  31.     ~Stars() {
  32.         delete _s;
  33.         _s = 0;
  34.     }
  35.     const char* get() const { return _s; }
  36.   private:
  37.     char* _s;
  38. };
  39. void banner(const Stars& st, const char* s) {
  40.                //=============
  41.     cout << st.get() << endl << s << endl;
  42. }
  43. int main() {
  44.     banner(40, Stars(40).get());
  45.          //===============
  46.     return 0;
  47. }
  48. ---
  49.  
  50. The program passes a pointer to the "_s" member of a "Stars" object
  51. to the "banner" function. This works for every compiler I have seen but I
  52. don't know if I can rely on this behaviour and prefer defining an auxiliary
  53. variable which is guaranteed to live until the function call returns.
  54.  
  55. Can anyone give me a hint?
  56.  
  57. TIA
  58. Bernd
  59.